

uniform vec3 color;
uniform sampler2D colorMap;

struct DirectionalLight {
  vec4 direction;
  vec4 colorAndIntensity;
};

struct PointLight {
  vec4 color;
  vec4 positionAndRadius;
};

struct SpotLight {
  vec4 color;
  vec4 positionAndLength;
  vec4 directionAndInnerAngle;
};

layout(std140) uniform Lights{
  vec4 ambientColor;
  int directionalLightCount;
  int spotLightCount;
  int pointLightCount;
  int pad;
  DirectionalLight directionalLights[4];
  PointLight pointLights[4];
  SpotLight spotLights[4];
};

layout(std140) uniform cameraData {
  mat4 viewMatrix;
  mat4 projMatrix;
  vec3 viewPos;
};

in ShaderData{
  vec3 worldPos;
  vec3 worldNormal;
  vec2 fragUv;
} fs_in;


in vec2 fragUv;
out vec4 fragColor;
uniform float shininess = 64;

float calcuteLight(vec3 toLight, vec3 fragNormal,vec3 toView){
  float diff = max(dot(fragNormal, toLight), 0.0);
  vec3 reflectDir = reflect(-toLight, fragNormal);
  float spec = pow(max(dot(toView, reflectDir), 0.0), shininess);
  return diff + spec;
}

vec3 calculateDirectionalLight(DirectionalLight light,vec3 fragPos,vec3 fragNormal,vec3 toView){
  float specAndDiff = calcuteLight(normalize(-light.direction.xyz),fragNormal,toView);
  return specAndDiff * light.colorAndIntensity.xyz * light.colorAndIntensity.w;
}

// vec3 CalcPointLight(PointLight light, vec3 fragPos, vec3 fragNormal,  vec3 viewDir)
// {
  

//     vec3 lightDir = normalize(light.positionAndRadius.xyz - fragPos);
//     float specAndDiff = calcuteLight(lightDir,fragNormal,viewDir)
//     float distance    = length(light.positionAndRadius.xyz - fragPos);
//     float attenuation = 1.0 / (light.constant + light.linear * distance + 
//                  light.quadratic * (distance * distance));    
//     // 合并结果
//     vec3 ambient  = light.ambient  * vec3(texture(material.diffuse, TexCoords));
//     vec3 diffuse  = light.diffuse  * diff * vec3(texture(material.diffuse, TexCoords));
//     vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
//     ambient  *= attenuation;
//     diffuse  *= attenuation;
//     specular *= attenuation;
//     return (ambient + diffuse + specular);
// }
 

void main(){

    vec3 viewDir = normalize(viewPos - fs_in.worldPos);

    vec3 dColors;
    for(int i = 0;i<directionalLightCount;++i){
       dColors += calculateDirectionalLight(directionalLights[i],fs_in.worldPos,normalize(fs_in.worldNormal),viewDir);
    }
    vec3 c = vec3(texture(colorMap,fs_in.fragUv));

    fragColor = vec4(c * dColors,1.0f);
}